package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLObjectDoing;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.Banner;
import com.rockcent.mall.lib.domain.Template;
import com.rockcent.mall.lib.domain.Template;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by zhangjh on 2016/11/16.
 */
@Component
public class TemplateRepositoryImpl implements TemplateRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(TemplateRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * @param mallId
     * @param whether
     * @param pageResult
     * @return
     */
    @Override
    public PageResult<Template> findTemplateQuery(Long mallId, Whether whether, PageResult pageResult) {


        SQLPageDoing<Template> doing = (sql, fields, params, typeReferenceMap) -> {

            sql.append("SELECT %s FROM templates p WHERE 1=1 ");
            fields.append("p.*");

            sql.append(" AND p.mall_id = :mallId");
            params.put("mallId", mallId);

            sql.append(" AND p.is_delete = :isDelete");
            params.put("isDelete", whether.toString());
            sql.append(" order by seq_no asc,date_created desc ");
        };
        return doing.go(pageResult, Template.class, objectMapper, jdbcTemplate, log);
    }

    @Override
    public Template findTemplateAbout(Integer seqNo, Long mallId, String direction) {
        SQLObjectDoing<Template> result = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM templates b" +
                    "  WHERE b.`is_delete`='NO' and b.`mall_id` = :mallId");
            if (direction.equals(Banner.UP)) {
                sql.append(" AND b.`seq_no` < :seqNo order by `seq_no` desc limit 1");
            }
            if (direction.equals(Banner.DOWN)) {
                sql.append(" AND b.`seq_no` > :seqNo order by `seq_no` asc limit 1");
            }
            params.put("mallId", mallId);
            params.put("seqNo", seqNo);
            fields.append("b.*");
            log.debug(sql.toString());
        };
        return result.go(Template.class, jdbcTemplate, log, objectMapper);
    }
}
